<?php

namespace App\Admin\Controllers;

use Encore\Admin\Grid;
use Encore\Admin\Form;
use App\Models\Comment;
use App\Models\Product;
use Encore\Admin\Layout\Content;
use Encore\Admin\Controllers\AdminController;

class CommentsController extends AdminController
{
    protected $title = '商品评论管理';
    
    protected function grid()
    {
        $grid = new Grid(new Comment());
        $grid->model()->where('commentable_type', Product::class)->orderByDesc('id');
	
	    if ($userId = request('user_id')) {
		    $grid->model()->where('user_id', $userId)->where('commentable_type', Product::class)->orderByDesc('id');
	    }

        $grid->column('id', 'ID');
        $grid->column('user_id', '会员')->display(function () {
	        return isset($this->user) ? "{$this->user->id}: {$this->user->name}" : '';
        });
        $grid->column('created_at', '创建时间')->display(function () {
	        return $this->created_at->toDatetimeString();
        });
        
        $grid->disableRowSelector();
        $grid->disableCreateButton();
        $grid->disableExport();
        
        $this->gridActions($grid);

        return $grid;
    }
    
    protected function gridActions(Grid $grid)
    {
	    $grid->actions(function (Grid\Displayers\Actions $actions) {
	    	$actions->disableView();
	    });
    }
	
	public function edit($id, Content $content)
	{
		return $content
			->title($this->title())
			->description($this->description['edit'] ?? trans('admin.edit'))
			->body($this->form($id)->edit($id));
	}
    
    protected function form($id = null)
    {
    	$comment = $id ? Comment::find($id) : null;
    	
        $form = new Form(new Comment());
        
        $form->display('content', '评论内容');
        $this->formImages($form, $comment);

	    $this->formTools($form);
        return $form;
    }
	
	protected function formImages(Form $form, Comment $comment = null)
	{
		if ($comment and $comment->images and count($comment->images) > 0) {
			foreach ($comment->images as $image) {
				if ($image) {
					$form->html(_form_image($image), '评论图像');
				}
			}
		}
	}
    
    protected function formTools(Form $form)
    {
    	$form->tools(function (Form\Tools $tools) {
    		$tools->disableView();
	    });
    }
}
